In Java, the try-catch block is used to handle exceptions and prevent the abnormal termination of the program.
Concept of try-catch Block The try block contains the code that might generate an exception. If an exception occurs inside the try block, it is caught and handled by the catch block. The catch block contains the code that is executed when an exception occurs.
Here’s the syntax of a try-catch block in Java:
try-catch block syntax
try {
// code that might generate an exception
} catch (Exception e) {
// code to handle the exception
}
Example of try-catch Block Here’s an example of a try-catch block in Java:
Basic example of a try-catch block in Java
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
} catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Output
ArithmeticException => / by zero
In this example, we are trying to divide a number by zero inside the try block, which causes an ArithmeticException. This exception is then caught and handled by the catch block.
Remember, proper exception handling can improve a Java application’s robustness and performance capabilities. It’s an essential part of writing a reliable and fault-tolerant Java program.